package com.ssy.wireless.task;

import com.ssy.wireless.entity.Enterprise;
import com.ssy.wireless.entity.HotspotOnlineStat;
import com.ssy.wireless.mapper.EnterpriseMapper;
import com.ssy.wireless.mapper.HotspotMapper;
import com.ssy.wireless.mapper.HotspotOnlineStatMapper;
import com.ssy.wireless.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by cofey on 16/11/22.
 */
@Component
@Slf4j
public class HotspotOnlineStatTask {
    @Autowired
    private EnterpriseMapper enterpriseMapper;
    @Autowired
    private HotspotMapper hotspotMapper;
    @Autowired
    private HotspotOnlineStatMapper hotspotOnlineStatMapper;

    //每天整点执行一次
    @Scheduled(cron = "0 0 0/1 * * ?")
    @Transactional
    public void exec() {
        Date date = DateUtils.getTime();
        log.info("热点在线统计任务,{}开始执行...", DateUtils.formatYMDHMS(date));
        List<Enterprise> enterprises = enterpriseMapper.select(null);
        Integer[] hotspotTypes = new Integer[]{1, 2};
        for (Enterprise enterprise : enterprises) {
            for (int hotspot : hotspotTypes) {
                int onlineCount = hotspotMapper.selectOnlineCount(enterprise.getId(), hotspot);
                if (onlineCount > 0) {
                    DateUtils.YearMonthWeekDayHour yearMonthWeekDay = DateUtils.getYearMonthWeekDay(date);
                    HotspotOnlineStat stat = new HotspotOnlineStat();
                    stat.setHourVal(yearMonthWeekDay.getHour());
                    stat.setDayVal(yearMonthWeekDay.getDay());
                    stat.setWeekVal(yearMonthWeekDay.getWeek());
                    stat.setMonthVal(yearMonthWeekDay.getMonth());
                    stat.setYearVal(yearMonthWeekDay.getYear());
                    stat.setCreateTime(date);
                    stat.setOnlineCount(onlineCount);
                    stat.setEntId(enterprise.getId());
                    stat.setHotspotType(hotspot);
                    hotspotOnlineStatMapper.insert(stat);
                } else {
                    log.info("企业{},类型{}没有在线热点数,无需统计", enterprise.getName(), hotspot);
                }
            }
            log.info("热点在线统计任务执行成功");
        }
    }
}
